/*
    Copyright 2010 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.util.sqs;

import com.xerox.amazonws.sqs2.*;
import com.norbl.util.*;
import java.util.*;

/**
 *
 * @author Barnet Wagman
 */
public class SqsOps {

    public static long MAX_WAIT_FOR_QUEUE_MILLIS =
                        1000L * 60L * 10L;

    private String awsAccessKeyID;
    private String awsSecretKey;

    public String queueName;
    public QueueService queueService;
    public MessageQueue queue;

    public SqsOps(String awsAccessKeyID, String awsSecretKey,
                  String queueName) {
        this.awsAccessKeyID = awsAccessKeyID;
        this.awsSecretKey = awsSecretKey;
        this.queueName = queueName;
        queueService =
            new QueueService(awsAccessKeyID, awsSecretKey,true);
        queue = getQueue(MAX_WAIT_FOR_QUEUE_MILLIS);
    }

    public SqsOps cleanClone() {
        return(new SqsOps(awsAccessKeyID,awsSecretKey,queueName) );
    }

    public void deleteAllMessages() throws SQSException {

        int nQueued;

        while ( (nQueued = queue.getApproximateNumberOfMessages()) > 0 ) {
            int n = Math.min(10,nQueued);
            Message[] messages =
                    queue.receiveMessages(Math.min(nQueued,10));
            for ( Message m : messages ) {
                queue.deleteMessage(m);
            }
            Time.nap(10L);
        }        
    }

    public List<Message> getAllMessages() throws SQSException {
        int nQueued;
        List<Message> messageList = new ArrayList<Message>();
        while ( (nQueued = queue.getApproximateNumberOfMessages()) > 0 ) {
            int n = Math.min(10,nQueued);
            Message[] messages =
                    queue.receiveMessages(Math.min(nQueued,10));
            for ( Message m : messages ) {
                messageList.add(m);
            }
            Time.nap(10L);
        }
        return(messageList);
    }

    public void deleteMessage(Message m) throws SQSException {
        queue.deleteMessage(m);
    }

        /** Blocks until the input queue is successfully obtained,
         *  up to a maximum time.
         */
    public MessageQueue getQueue(long maxWaitMillis) {

        long t0 = System.currentTimeMillis();

        SQSException x = null;

        for(;;) {
            try {
                MessageQueue q = queueService.getOrCreateMessageQueue(queueName);

                if ( q != null ) return(q);
            }
            catch(SQSException sqx) {
                System.out.println("RunnerNode.getQueue():\n" + sqx);
                x = sqx;
            }

            try { Thread.sleep(1000L); }
            catch(InterruptedException ix) {}

            if ( (System.currentTimeMillis() - t0) > maxWaitMillis ) {
                String m = "Exceeded max wait=" + maxWaitMillis + " millis.";
                if ( x != null )  m += "\n" + x.toString();
                throw new TimedOutWaitingForQueueException(m);
            }
        }
    }
    
}
